package com.finance.cooperate.feature.web.controller;

import com.finance.cooperate.common.constant.CodeMsg;
import com.finance.cooperate.common.pojo.RestResult;
import com.finance.cooperate.common.utils.StringUtil;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.feature.service.ApplyService;
import com.finance.cooperate.feature.service.ModelService;
import com.finance.cooperate.feature.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName ModelController
 * @Description TODO
 * @Author shen
 * @Date 2023/8/3 16:38
 * @Modify ...
 */
@Slf4j
@RestController
@RequestMapping("/api/v1.0/credit")
public class ModelController {

    @Autowired
    private ModelService modelService;

    @Autowired
    private CooperateRequestScope requestScope;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private UserService userService;

    /**
     * @Author shen
     * @Description 模型执行
     * @Date 1:43 下午 2021/3/11
     * @Param [uid, loanNum]
     * @return cm.finance.crm.common.pojo.RestResult
     **/
    @PostMapping
    public RestResult execution(String applyId, Long loanNum) {

        try {

            log.info("applyId：" + applyId);

            // 检查参数
            if (StringUtil.isEmptyOrNvl(applyId) || StringUtil.isEmptyOrNvl(loanNum)) {
                return RestResult.build(CodeMsg.PARAMS_NULL);
            }

            if (loanNum < 1) {
                return RestResult.build(CodeMsg.PARAMS_ERROR);
            }

            requestScope.setLoanNum(loanNum);

            requestScope.setApplyId(applyId);

            // 根据 applyId 查询出用户 id
            String uid = applyService.getUidByApplyId(applyId);

            if (StringUtil.isEmptyOrNvl(uid)) {
                // 说明有问题
                return RestResult.build(CodeMsg.USER_ID_PARAMS_NULL);
            }

            requestScope.setUserId(uid);

            // 缓存设备id

            try {

                String deviceId = userService.getDeviceId(uid);

                requestScope.setDeviceId(deviceId);

            } catch (Exception e) {
                e.printStackTrace();
            }


            return modelService.execution(uid, loanNum);


        } catch (Exception e) {

            log.error("Service Error: ", e);

            e.printStackTrace();
        }

        return RestResult.build(CodeMsg.SYSTEM_ERROR);

    }


}
